#!/usr/bin/python 

from scapy.all import *
import time
import rule
import match
import action
import tool
import kmeans

K = 2
tool = tool.tool()
myip = tool.getMyIp()
mymac = tool.getMyMac()
replymem = {}
deltamem = {}
dropmem = []

def runIcmp(dip,dmac,dtos):
    pkt = Ether(dst=dmac,type=0x0800)/IP(dst=dip,proto=1,tos = dtos)/ICMP(type=8) #Dot1Q(vlan=10)
    m = match.match(dl_src=mymac,dl_dst=dmac,nw_src=myip,nw_dst=dip,nw_tos=dtos,nw_proto="icmp",dl_type = "ip")
    rtt = []
    for i in range(1,4):
        ans,unans = srp(pkt,verbose=0,timeout=10)
        if(len(ans) != 0):
            rx = ans[0][1]
            tx = ans[0][0]
            #print tx.sent_time
            #print rx.time
            rt = (rx.time - tx.sent_time)*1000
            rtt.append(round(rt))
            #print i
            if i == 1:
                print "------m-------"
                print m.__dict__
            print rtt[i-1]
        else:
            dropmem.append(m)
            break
    if i != 1:
        replymem[m] = rtt[0]
        deltamem[m] = rtt[0] - rtt[-1]

def runTcp(dip,dmac,dtos,sp,dp):
    pkt = Ether(dst=dmac,type=0x0800)/IP(dst=dip,proto=6,tos=dtos)/TCP(sport=sp,dport=dp)#,flags = "S")
    m = match.match(dl_src=mymac,dl_dst=dmac,dl_type="ip",nw_src=myip,nw_dst=dip,nw_tos=dtos,nw_proto="tcp",tp_src=sp,tp_dst=dp)
    rtt = []
    for i in range(1,4):
        ans, unans = srp(pkt,verbose=0,timeout=10)
        if(len(ans) != 0):
            rx = ans[0][1]
            tx = ans[0][0]
            #print tx.sent_time
            #print rx.time
            rt = (rx.time - tx.sent_time)*1000
            rtt.append(round(rt))
            if i == 1:
                print "------m-------"
                print m.__dict__
            print rtt[i-1]
        else:
            dropmem.append(m)
            break
    if i != 1:
        replymem[m] = rtt[0]
        deltamem[m] = rtt[0] - rtt[-1]

def runUdp(dip,dmac,dtos,sp,dp):
    dp = 5001
    pkt = Ether(dst=dmac,type=0x0800)/IP(dst=dip,proto=17,tos=dtos)/UDP(sport=sp,dport=dp)
    m = match.match(dl_src=mymac,dl_dst=dmac,dl_type="ip",nw_src=myip,nw_dst=dip,nw_tos=dtos,nw_proto="udp",tp_src=sp,tp_dst=dp)
    rtt = []
    for i in range(1,4):
        ans, unans = srp(pkt,verbose=0,timeout=10)
        if(len(ans) != 0):
            rx = ans[0][1]
            tx = ans[0][0]
            #print tx.sent_time
            #print rx.time
            rt = (rx.time - tx.sent_time)*1000
            rtt.append(round(rt))
            if i == 1:
                print "------m-------"
                print m.__dict__
            print rtt[i-1]
        else:
            dropmem.append(m)
            break
    if i != 1:
        replymem[m] = rtt[0]
        deltamem[m] = rtt[0] - rtt[-1]

#def runArp():
    #to do 

def readARPtable():
    iplist=[]
    maclist=[]
    output = subprocess.Popen(["arp", "-n"],stdout=subprocess.PIPE)
    while True:
        line=output.stdout.readline()
        #print line
        if line !='':
            #line_s = line.split(" ")
	    line_s = line.split()
            #print line_s
            #line_s = filter(lambda a: a !="",line_s)
	    #print(line_s)
	    #print("------------------")
	    #print line_s[0][:1]
            if line_s[0][:1].isdigit() and line_s[2][:1].isdigit():
                iplist.append(line_s[0])
                maclist.append(line_s[2])
        else:
            break
    #print iplist
    #print maclist
    return iplist,maclist

def loop():
    iplist,maclist=readARPtable()
    iplist.sort()
    maclist.sort()
    print iplist,maclist
    for i in range(0,4):
        for tos in range(101,102):
            #runIcmp(iplist[i],maclist[i],tos)
            for sp in range(1001,1002):
                for dp in range(10002,10003):
                    runTcp(iplist[i+4],maclist[i],tos,sp,dp)
                    runUdp(iplist[i+4],maclist[i],tos,sp,dp)

    for j in range(0,4):
        for to in range(101,102):
            runIcmp(iplist[j+4],maclist[j],to)

def clsfy(replymem):
    replymemlist = sorted(replymem.items(), key=lambda replymem:replymem[1])
    rttlist = [replymemlist[i][1] for i in range(len(replymemlist))]
    
    rttcluster = kmeans.run(rttlist, K)
    layers = [[] for i in range(K)]
    layers2 = [[] for i in range(K)]
    classnumber = 0
    classid = int(rttcluster[:,0][0])
    for i in range(rttcluster.shape[0]):
        if classid != int(rttcluster[:,0][i]):
            classnumber = classnumber+1
            classid = int(rttcluster[:,0][i])
        rmatch = replymemlist[i][0]
        rrtt = replymemlist[i][1]
        layers[classnumber].append(rmatch)
        layers2[classnumber].append(rrtt)
    #print "Result : ",layers
    print "value :",layers2
    return layers

    
'''
def icmp(dip, dmac, count):
    #builNet.py ---> autoStaticArp=True
    #arp = Ether()/ARP(op="who-has",hwdst="00:00:00:00:00:00", pdst="10.0.0.1")
    #arp = Ether()/ARP(op="is-at",hwdst=dmac, pdst=dip)
    #print "send"
    #sendp(arp)
    #sendp(arp)
    #sendp(arp)
    #time.sleep(1)

    ether = Ether(dst = dmac,type=0x0800)
    ip = IP(dst = dip,proto =1)
    icmp = ICMP(type = 8)
    #data = Raw('i'*2048)
    #print len(data)
    
    pkt = ether/ip/icmp#/data
    #print len(pkt)
    total = 0.0
    a = 0
    for i in range(count):
        #ans,unans = srp(fragment(pkt),verbose=0,timeout=10)
        ans,unans = srp(pkt,verbose=0,timeout=10)
        if(len(ans) != 0):
            rx = ans[0][1]
            tx = ans[0][0]
            delta = rx.time - tx.sent_time
            #print("icmp time delay: ",delta*1000)
            #revise
            if i > 4:
                if delta*1000 < 200:
                    total += delta
                else:
                    a = a + 1
        else:
            print("fail")
    #print "actual count times",count-a
    return total/(count-a)*1000

def tcpsyn(dip, dmac,dp,sp,count=5):
    eth=Ether(dst=dmac,type = 0x0800)
    ip=IP(dst=dip, proto = 6, tos = 1)
    tcp=TCP(sport=sp, dport=dp, flags="S",seq=1000)
    tcpsyn=eth/ip/tcp
    for i in range(count):
        ans,unans=srp(tcpsyn, verbose=0)
        print ans
        #ans.show()
        #unans.show()
        if(len(ans) != 0):
            rx = ans[0][1]
            tx = ans[0][0]
            print tx.sent_time
            print rx.time
            delta = rx.time - tx.sent_time
            print "delta : ",delta*1000
        #time.sleep(1)
        #print ans
   # print synack
   '''
if __name__ == "__main__":
    '''a = raw_input("dst host number:")
    print "00:00:00:00:00:0" + hex(int(a)).split('x')[1]
    average = tcpsyn("10.0.0." + a, "00:00:00:00:00:0" + hex(int(a)).split('x')[1],5001,20,1)
    print average
    '''
    readARPtable()
    loop()
    #exit()
    print len(replymem),replymem.values()
    print "----------------------------"
    print len(deltamem),deltamem.values()
    print "------------------------------------------"
    print len(dropmem)
    print "Drop match:"
    for m in dropmem:
        print m.__dict__
    print "=============================="
    rfm = clsfy(replymem)
    print "++++++++++++++++++++++++++++++"
    print "Match1 from rtt:"
    for n in rfm[0]:
        print n.__dict__
    print "=============================="

    print replymem.items()
    dfm = clsfy(deltamem)
    print "Match2 from delta:"
    for l in dfm[0]:
        print l.__dict__
    print "++++++++++++++++++++++++++++++"
    print "Result: "
    for x in dfm[0]:
        for y in rfm[0]:
            if x == y:
                print x.__dict__
